﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Emico.Linq.Criterion
{
    public static class CriteriaHelper
    {
        public static string SerializeToString<T>(Criteria<T> criteria) 
            where T : class
        {
            byte[] bytes = SerializeToBinary<T>(criteria);
            return Convert.ToBase64String(bytes);            
        }

        public static Criteria<T> DeserializeFromString<T>(string source)
            where T : class
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException("source");
            }

            return DeserializeFromBinary<T>(Convert.FromBase64String(source));
        }

        public static byte[] SerializeToBinary<T>(Criteria<T> criteria)
            where T : class
        {
            if (criteria == null)
            {
                throw new ArgumentNullException("criteria");
            }

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, criteria);
                return ms.ToArray();
            }
        }

        public static Criteria<T> DeserializeFromBinary<T>(byte[] bytes)
            where T : class
        {
            if (bytes == null)
            {
                throw new ArgumentNullException("bytes");
            }

            using (MemoryStream ms = new MemoryStream(bytes))
            {
                BinaryFormatter bf = new BinaryFormatter();
                return (Criteria<T>)bf.Deserialize(ms);
            }
        }
    }
}
